const { router, fs, urlencodedParser } = require('../CustomMethod');
const database = require('../CustomMethod/mysqlMethod');
const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const destPath = path.join(__dirname, 'avatar');
        cb(null, destPath);
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop());
    }
});

const upload = multer({ storage: storage });

const executeQuery = (res, query, params, successMsg, errorMsg, updated) => {
    database(query, params, function (err, result) {
        if (err) {
            res.send({ code: 0, module: errorMsg });
            return;
        }
        res.send({ code: 200, module: successMsg, result, updated });
    });
};

// 修改头像
router.post('/avatar', upload.single('image'), function (req, res, next) {
    if (!req.file) {
        return res.status(400).send('没有文件被上传');
    }
    let id = req.body.id;
    let filePath = '/public/JS/router/avatar/' + req.file.filename;
    executeQuery(res, 'UPDATE userinformation SET avatar = ?  WHERE Id = ?', [filePath, id], "头像修改成功", "头像修改失败", filePath);
});

module.exports = router;